package cn.liccshop.sys.exception;

import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.entity.ErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: LiCCShop
 * @description: 全局异常配置
 * @author: LiCC
 * @data 2019-02-15-21:09
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * @description 捕获自定义异常
     * @param request
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(MySystemException.class)
    public ErrorResponse systemExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response){
        log.error("自定义异常", e);
        e.printStackTrace();
        MySystemException exception = (MySystemException) e;
        return new ErrorResponse(exception.getCode(), exception.getMessage());
    }

    /**
     * @description 捕获运行时异常
     * @param request
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public ErrorResponse runtimeExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response){
        log.error("运行时异常", e);
        e.printStackTrace();
        RuntimeException exception = (RuntimeException) e;
        return new ErrorResponse(Constants.SYS_ERROR, exception.getMessage());
    }

}
